#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>

void mount_webdav(const char *mount_point, const char *webdav_url) {
    // 创建挂载点目录
    if (mkdir(mount_point, 0755) == -1) {
        perror("Error creating mount point");
        exit(EXIT_FAILURE);
    }

    // 使用 curlftpfs 挂载 WebDAV 网盘
    pid_t pid = fork();
    if (pid == -1) {
        perror("Error forking");
        exit(EXIT_FAILURE);
    } else if (pid == 0) {
        // 在子进程中执行挂载
        execlp("curlftpfs", "curlftpfs", webdav_url, mount_point, "-o", "user=username:password", NULL);
        perror("Error executing curlftpfs");
        exit(EXIT_FAILURE);
    } else {
        // 在父进程中等待挂载完成
        int status;
        waitpid(pid, &status, 0);
        if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
            printf("WebDAV mounted successfully at %s\n", mount_point);
        } else {
            fprintf(stderr, "Failed to mount WebDAV at %s\n", mount_point);
            exit(EXIT_FAILURE);
        }
    }
}

void unmount_webdav(const char *mount_point) {
    // 使用 fusermount 卸载 WebDAV 网盘
    pid_t pid = fork();
    if (pid == -1) {
        perror("Error forking");
        exit(EXIT_FAILURE);
    } else if (pid == 0) {
        // 在子进程中执行卸载
        execlp("fusermount", "fusermount", "-u", mount_point, NULL);
        perror("Error executing fusermount");
        exit(EXIT_FAILURE);
    } else {
        // 在父进程中等待卸载完成
        int status;
        waitpid(pid, &status, 0);
        if (WIFEXITED(status) && WEXITSTATUS(status) == 0) {
            printf("WebDAV unmounted successfully from %s\n", mount_point);
        } else {
            fprintf(stderr, "Failed to unmount WebDAV from %s\n", mount_point);
            exit(EXIT_FAILURE);
        }
    }

    // 删除挂载点目录
    if (rmdir(mount_point) == -1) {
        perror("Error removing mount point");
        exit(EXIT_FAILURE);
    }
}

int main(int argc, char *argv[]) {
    if (argc != 4) {
        fprintf(stderr, "Usage: %s [mount|unmount] [mount_point] [username:password@webdav_address:port]\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    const char *action = argv[1];
    const char *mount_point = argv[2];
    const char *webdav_url = argv[3];

    if (strcmp(action, "mount") == 0) {
        mount_webdav(mount_point, webdav_url);
    } else if (strcmp(action, "unmount") == 0) {
        unmount_webdav(mount_point);
    } else {
        fprintf(stderr, "Invalid action. Use 'mount' or 'unmount'.\n");
        exit(EXIT_FAILURE);
    }

    return 0;
}
